<?php
/**
 * Make Open AI call to fetch result
 */
function seedprod_pro_call_open_ai() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {

		if ( ! current_user_can( apply_filters( 'seedprod_lpage_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		$seedprod_api_key = seedprod_pro_get_api_key();
		$api_key          = $seedprod_api_key;
		$token            = get_option( 'seedprod_token' );
		$api_token        = get_option( 'seedprod_api_token' );

		$prompt = isset( $_REQUEST['prompt'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['prompt'] ) ) : '';
		$data   = array(
			'prompt'    => $prompt,
			'api_token' => $api_token,
			'api_key'   => $api_key,
			'token'     => $token,
		);

		$headers = array(
			'Accept'        => 'application/json',
			'Authorization' => 'Bearer ' . $api_token,
		);

		$url = SEEDPROD_PRO_WEB_API_URL . 'v4/openaigenerate';

		try {

			$response = wp_remote_post(
				$url,
				array(
					'body'      => wp_json_encode( $data ),
					'headers'   => $headers,
					'sslverify' => false,
					'timeout'   => 60,
				)
			);

			if ( is_wp_error( $response ) ) {

				$curl_error = $response->get_error_code();
				if ( 'http_request_failed' === $curl_error ) {
					$result = wp_json_encode( array( 'error' => __( 'cURL error:', 'seedprod-pro' ) . $response->get_error_message() ) );
				} else {
					$result = wp_json_encode( array( 'error' => $response->get_error_message() ) );
				}
			} else {
				$http_status = wp_remote_retrieve_response_code( $response );
				if ( 200 === $http_status ) {
					$response_body = wp_remote_retrieve_body( $response );
					$result_data   = json_decode( $response_body, true );

					if ( null === $result_data && json_last_error() !== JSON_ERROR_NONE ) {
						$result = wp_json_encode( array( 'error' => __( 'Invalid JSON response', 'seedprod-pro' ) ) );
					} else {
						$result = wp_json_encode( $result_data );
					}
				} else {
					// Request timeout error.
					$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
				}
			}
		} catch ( Exception $e ) {
			$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
		}

		echo wp_kses_post( $result );

		exit;

	}
}

/**
 * Make Open AI call to fetch result with instruction for model.
 */
function seedprod_pro_call_open_ai_edit() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {

		if ( ! current_user_can( apply_filters( 'seedprod_lpage_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		$seedprod_api_key = seedprod_pro_get_api_key();
		$api_key          = $seedprod_api_key;
		$token            = get_option( 'seedprod_token' );
		$api_token        = get_option( 'seedprod_api_token' );

		$prompt      = isset( $_REQUEST['prompt'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['prompt'] ) ) : '';
		$instruction = isset( $_REQUEST['instruction'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['instruction'] ) ) : '';
		$data        = array(
			'prompt'      => $prompt,
			'instruction' => $instruction,
			'api_token'   => $api_token,
			'api_key'     => $api_key,
			'token'       => $token,
		);

		$headers = array(
			'Accept'        => 'application/json',
			'Authorization' => 'Bearer ' . $api_token,
		);

		$url = SEEDPROD_PRO_WEB_API_URL . 'v4/openaiedittext';

		try {
				$response = wp_remote_post(
					$url,
					array(
						'body'      => wp_json_encode( $data ),
						'headers'   => $headers,
						'sslverify' => false,
						'timeout'   => 60,
					)
				);

			if ( is_wp_error( $response ) ) {
				$curl_error = $response->get_error_code();
				if ( 'http_request_failed' === $curl_error ) {
					$result = wp_json_encode( array( 'error' => __( 'cURL error:', 'seedprod-pro' ) . $response->get_error_message() ) );
				} else {
					$result = wp_json_encode( array( 'error' => $response->get_error_message() ) );
				}
			} else {

				$http_status = wp_remote_retrieve_response_code( $response );

				if ( 200 === $http_status ) {
					$response_body = wp_remote_retrieve_body( $response );
					$result_data   = json_decode( $response_body, true );
					$result        = wp_json_encode( $result_data );
				} else {
					// Request timeout error.
					$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
				}
			}
		} catch ( Exception $e ) {
			$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
		}

		echo wp_kses_post( $result );

		exit;

	}
}


/**
 * Make Open AI call to fetch user credits available.
 */
function seedprod_pro_call_ai_credits() {
	if ( check_ajax_referer( 'seedprod_nonce' ) ) {

		if ( ! current_user_can( apply_filters( 'seedprod_lpage_capability', 'edit_others_posts' ) ) ) {
			wp_send_json_error();
		}

		$seedprod_api_key = seedprod_pro_get_api_key();
		$api_key          = $seedprod_api_key;
		$token            = get_option( 'seedprod_token' );
		$api_token        = get_option( 'seedprod_api_token' );

		$data = array(
			'api_token' => $api_token,
			'api_key'   => $api_key,
			'token'     => $token,
		);

		$headers = array(
			'Accept'        => 'application/json',
			'Authorization' => 'Bearer ' . $api_token,
		);

		$url = SEEDPROD_PRO_WEB_API_URL . 'v4/openaicredits';

		try {

			$response = wp_remote_post(
				$url,
				array(
					'body'      => wp_json_encode( $data ),
					'headers'   => $headers,
					'sslverify' => false,
					'timeout'   => 60,
				)
			);

			if ( is_wp_error( $response ) ) {

				$curl_error = $response->get_error_code();
				if ( 'http_request_failed' === $curl_error ) {
					$result = wp_json_encode( array( 'error' => __( 'cURL error:', 'seedprod-pro' ) . $response->get_error_message() ) );
				} else {
					$result = wp_json_encode( array( 'error' => $response->get_error_message() ) );
				}
			} else {
				$http_status = wp_remote_retrieve_response_code( $response );
				if ( 200 === $http_status ) {
					$response_body = wp_remote_retrieve_body( $response );
					$result_data   = json_decode( $response_body, true );

					if ( null === $result_data && json_last_error() !== JSON_ERROR_NONE ) {
						$result = wp_json_encode( array( 'error' => __( 'Invalid JSON response', 'seedprod-pro' ) ) );
					} else {
						$result = wp_json_encode( $result_data );
					}
				} else {
					// Request timeout error.
					$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
				}
			}
		} catch ( Exception $e ) {
			$result = wp_json_encode( array( 'error' => __( 'Server error or request timeout. Try again later.', 'seedprod-pro' ) ) );
		}

		echo wp_kses_post( $result );

		exit;

	}
}
